<template>
    <div>
        
        <div style="margin-bottom: 10px">
            <i-button type="info" @click="btn_refresh"  style="margin-right: 10px">刷新</i-button> 
            <i-button type="primary" style="margin-right: 10px"  @click="btn_edit_dr">修改版本</i-button>
            <i-button type="primary" style="margin-right: 10px"  @click="btn_add_breaker">添加熔断</i-button>
            <i-button type="error" style="margin-right: 10px"  @click="btn_del_breaker">删除熔断</i-button>
            <i-button type="primary" style="margin-right: 10px" @click="btn_add_load_balancer">添加负载均衡</i-button>
            <i-button type="error" style="margin-right: 10px"  @click="btn_del_load_balance">删除负载均衡</i-button>
            <!-- 支持批量删除 -->
            <i-button type="error" style="margin-right: 10px"  @click="btn_del_dr">删除dr</i-button>

        </div>
        <i-table border stripe  :columns="format" :data="show_list" @on-selection-change="onSelect" :height="sharedState.tableHeight" >
            <!-- <template slot-scope="{ row, index }" slot="action">
                <Button type="error" style="margin-bottom: 5px "  @click="del_destination_rule(index)">删除</Button>
            </template> -->
        </i-table >
        <div style="text-align: center;margin-top: 10px;">
            <Page ref="page" :total="total" :page-size="pageSize"  @on-change="changePage" show-total/>
        </div>
        <!-- 添加熔断模态框  -->
        <Modal v-model="show_add_breaker_modal" width="600">
            <p slot="header" style="color:#f60;text-align:center">
                {{ dr_name }}<span>增加熔断</span>
            </p>
            <div style="">
                <Form ref="breaker" :model="breaker" :rules="breaker_rules" label-position="left"  :label-width="150">
                    <!-- 连接池tcp -->
                    <!-- {{ breaker.connectionPool.tcp.maxConnections }} -->
                    <!-- {{ breaker.outlierDetection.maxEjectionPercent }} -->
                    <Form-Item label="tcp最大连接数:"  prop="maxConnections">
                        <Input type="number"  v-model="breaker.maxConnections" />
                    </Form-Item>
                    <!-- 连接池http -->
                    <Form-Item label="http1最大pending请求数:"  prop="http1MaxPendingRequests">
                        <Input type="number"  v-model="breaker.http1MaxPendingRequests" />
                    </Form-Item>
                    <Form-Item label="每连接最大http请求数:"  prop="maxRequestsPerConnection">
                        <Input type="number"  v-model="breaker.maxRequestsPerConnection" />
                    </Form-Item>
                    <!-- 外部检测 -->
                    <Form-Item label="连续错误数:"  prop="consecutiveErrors">
                        <Input type="number"  v-model="breaker.consecutiveErrors" />
                    </Form-Item>
                    <Form-Item label="间隔:"  prop="interval">
                        <Input type="text"  v-model="breaker.interval" />
                    </Form-Item>
                    <Form-Item label="拒绝时间:"  prop="baseEjectionTime">
                        <Input type="text"  v-model="breaker.baseEjectionTime" />
                    </Form-Item>
                   <Form-Item label="拒绝比例:"  prop="maxEjectionPercent">
                        <Input type="number"  v-model="breaker.maxEjectionPercent" />
                    </Form-Item>
                </Form> 
               
            </div>
            <div slot="footer">
                 <p style="text-align: left"> 说明: </p>
                <Button type="primary" size="large"  @click="submit_add_breaker('breaker')">提交</Button>
            </div>
        </Modal>
        <Modal v-model="show_add_balancer_modal" width="600">
            <p slot="header" style="color:#f60;text-align:center">
                {{ dr_name }}<span>增加负载均衡</span>
            </p>
            <div>
                <Form ref="balancer" :model="balancer" label-position="left"  :label-width="150">
                    <Form-Item label="选择负载均衡simple算法" prop="simple">
                        <Select v-model="balancer.simple">
                            <Option v-for="simple in simple_algorithm_list" :key="simple" :value="simple">{{ simple }}</Option>
                        </Select>
                    </Form-Item> 
                </Form> 
            </div>
            <div slot="footer">
                <Button type="primary" size="large"  @click="submit_add_balancer()">提交</Button>
            </div>
        </Modal>
        <!-- 修改subset版本Modal -->
        <Modal v-model="show_edit_dr_modal" width="600">
            <p slot="header" style="color:#f60;text-align:center">
                {{ dr_name }}<span>修改dr</span>
            </p>
            <div>
                <Form ref="versions" :model="versions" label-position="left"  :label-width="150">
                    <Form-Item label="old：" prop="old">
                        <Input type="text"  v-model="versions.old" />
                    </Form-Item> 
                    <Form-Item label="new:" prop="new">
                        <Input type="text"  v-model="versions.new" />
                    </Form-Item> 
                </Form> 
            </div>
            <div slot="footer">
                <Button type="primary" size="large"  @click="submit_edit_dr">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>

import {k8s_namespace_post} from '@/api/http'
import { 
get_destination_rule_list,
update_breaker,
delete_breaker,
update_loadBalancer,
delete_loadBalancer,
delete_dr,
update_versions} from  '@/api'

// update_breaker,update_loadBalancer 
import {
    multi_delete_namespace_resource,
    delete_namespace_resource,
    // get_placement
} from  '@/common/util'
import store from '@/store'
export default {
    data() {
        const validatePercent = (rule,value,callback) => {
            if(value <1 || value > 100) {
                callback(new Error('请输入1-100整数'))
            }else{
                callback();
            }
        };
        const validateNumber = (rule,value,callback) => {
            console.log(typeof value)
            if(!(/(^[1-9]\d*$)/.test(value))) {
                callback(new Error('请输入数字'))
            }else{
                callback();
            }
        };
        return {
            sharedState: store.state,
            format: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '名字',key: 'name'
                },
                {
                    title: '命名空间',key: 'namespace'
                },
                {
                    title: 'host',key: 'host',
                },
                {
                    title: '版本定义',key: 'subsets',width:300,
                    render : (h,params) => {
                        let subsets = params.row.subsets 
                        if (subsets == null ){
                            return   h('p','无')
                        }else{
                            let value=''
                            for(let i=0;i<subsets.length;i++){
                                let subset = subsets[i]
                                let name = subset['name']
                                let version = subset['labels']['version']
                                let item = name+":"+version
                                value += item
                                console.log(value)
                                if(i != subsets.length-1){
                                    value += "\n"
                                    console.log(value)
                                }
                            }
                            return h('p',value)
                        }
                    }
                },
                {
                    title: '流量分发策略',key: 'trafficPolicy',width:400,
                    render: (h, params) => {
                        return h('div', [
                            h('pre', JSON.stringify(params.row.trafficPolicy,undefined,4))
                        ]);
                    }
                },
                {
                    title: '创建时间',key: 'create_time'
                },
                // {
                //     title: '操作',slot: 'action',width: 100,align: 'center'
                // }

            ],
            total_list: [],
            show_list: [],
            // 分页
            total: 0,
            pageSize: 15,
            // 多选框
            selecteds: [],
            // 添加熔断
            dr_name: null,
            show_add_breaker_modal: false,
            breaker: {
                // tcp  
                maxConnections:null,
                // http
                http1MaxPendingRequests: 1,
                maxRequestsPerConnection:1,
                // error
                consecutiveErrors: 1,
                interval: '1s',
                baseEjectionTime:'3m',
                maxEjectionPercent: 100,
            },
            breaker_rules:{
                // 这里不输入的话会出现问题
                maxConnections: [
                    // {required: true,message:'请输入最大连接数',trigger: 'blur'},
                    { validator: validateNumber,trigger: 'blur'},

                ],
                maxEjectionPercent: [
                    {trigger:'blur',transform(value){return Number(value);},validator: validatePercent}
                ],
            },
            // 添加负载均衡
            show_add_balancer_modal:false,
            balancer:{
                simple: 'ROUND_ROBIN',
            },
            simple_algorithm_list: ['ROUND_ROBIN','LEAST_CONN','RANDOM'],
            // 编辑dr
            show_edit_dr_modal:false,
            versions: {
                old: '',
                new: '',
            },

        }
    },
    methods: {
        btn_refresh(){
            setTimeout(() =>{
                this.refresh();
            },200); 
        },
        // 提交编辑dr
        submit_edit_dr(){
            let data={"name": this.dr_name,"versions":this.versions}
            k8s_namespace_post(update_versions,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('修改dr版本成功')
                    this.show_edit_dr_modal = false
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },
        // 点击编辑dr事件
        btn_edit_dr(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            // 为后续操作准备好dr的名称
            this.dr_name = name
            let subsets = this.selecteds[0].subsets
            for(let i=0;i<subsets.length;i++){
                if (subsets[i].name == 'old'){
                    this.versions.old = subsets[i].labels.version
                }else if (subsets[i].name == 'new'){
                    this.versions.new  = subsets[i].labels.version
                }else {
                    this.$Message.error("获取不到正确的版本号")
                    return
                }
            }
            console.log(this.versions)
            
            this.show_edit_dr_modal = true      
        },
        // 提交负载均衡
        submit_add_balancer(){
            let data={"name":this.dr_name,"loadBalancer":this.balancer}
            k8s_namespace_post(update_loadBalancer,data).then( (response) => {
                    let info = JSON.stringify(response.data)
                    if(info.indexOf('ok') != -1) {
                        this.$Message.success('添加负载均衡策略成功')
                        this.show_add_balancer_modal = false
                        this.refresh()
                    }else {
                        alert(info)
                    }
                })
        },
        // 点击添加负载均衡
        btn_add_load_balancer(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            this.dr_name = name
            this.show_add_balancer_modal = true
        },
        // 点击删除负载均衡
        btn_del_load_balance(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            let namespace = this.selecteds[0].namespace
            let result = confirm("确定要删除"+name+"吗?")
            if(result == false) return 
            delete_namespace_resource(namespace,name,delete_loadBalancer)
            this.refresh()
        },
        // 提交熔断
        submit_add_breaker(name){
            let validate = false
            this.$refs[name].validate((valid) => {
                if (valid) validate = true
            })
            if(!validate) return
            let maxConnections = parseInt(this.breaker.maxConnections)
            let http1MaxPendingRequests =parseInt(this.breaker.http1MaxPendingRequests)
            let maxRequestsPerConnection =parseInt(this.breaker.maxRequestsPerConnection)
            let consecutiveErrors =parseInt(this.breaker.consecutiveErrors)
            let interval = this.breaker.interval
            let baseEjectionTime = this.breaker.baseEjectionTime
            let maxEjectionPercent =parseInt(this.breaker.maxEjectionPercent)
            let breaker = {
                 'connectionPool': {
                     'tcp':{
                         'maxConnections':maxConnections,
                     },
                     'http':{
                         'http1MaxPendingRequests':http1MaxPendingRequests,
                         'maxRequestsPerConnection':maxRequestsPerConnection,
                     },
                 },
                 'outlierDetection':{
                     'consecutiveErrors': consecutiveErrors,
                     'interval': interval,
                     'baseEjectionTime':baseEjectionTime,
                     'maxEjectionPercent': maxEjectionPercent,
                 },
             }
            let data={"name":this.dr_name,"breaker":breaker}
            k8s_namespace_post(update_breaker,data).then( (response) => {
                let info = JSON.stringify(response.data)
                if(info.indexOf('ok') != -1) {
                    this.$Message.success('恭喜你，添加熔断成功')
                    this.show_add_breaker_modal = false
                    this.refresh()
                }else {
                    alert(info)
                }
            })
        },
        // 点击添加熔断
        btn_add_breaker(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            this.dr_name = name
            // 把熔断已有数据保存到data中
            let trafficPolicy = this.selecteds[0].trafficPolicy
            console.log("trafficPolicy:",trafficPolicy)
            
            if(trafficPolicy){
                if(trafficPolicy.connectionPool){
                    let connectionPool = trafficPolicy.connectionPool
                    this.breaker.maxConnections = connectionPool.tcp.maxConnections
                    this.breaker.http1MaxPendingRequests = connectionPool.http.http1MaxPendingRequests
                    this.breaker.maxRequestsPerConnection = connectionPool.http.maxRequestsPerConnection
                }
                if(trafficPolicy.outlierDetection){
                    let outlierDetection = trafficPolicy.outlierDetection
                    this.breaker.consecutiveErrors = outlierDetection.consecutiveErrors
                    this.breaker.interval = outlierDetection.interval
                    this.breaker.baseEjectionTime = outlierDetection.baseEjectionTime
                    this.breaker.maxEjectionPercent = outlierDetection.maxEjectionPercent
                }
            }

            
            this.show_add_breaker_modal = true
        },
        // 点击删除熔断
        btn_del_breaker(){
            if(!this.check()) return
            let select_count = this.selecteds.length
            if (select_count > 1){
                this.$Message.error("此操作暂时不能批量")
                return false
            }
            let  name = this.selecteds[0].name
            let namespace = this.selecteds[0].namespace
            let result = confirm("确定要删除"+name+"吗?")
            if(result == false) return 
            delete_namespace_resource(namespace,name,delete_breaker)
            this.refresh()
        },
        // 删除dr点击事件
        btn_del_dr(){
            if(!this.check()) return
            let namespace = localStorage.getItem('currentNameSpace')
            if(namespace == 'all' || namespace==null || namespace == ''){
                this.$Message.error("请选择具体命名空间")
                return
            }
            let name_list = []
            for(let i=0;i<this.selecteds.length;i++){
                name_list[i]  = this.selecteds[i].name
            }
            let result = confirm("确定要删除"+name_list+"吗?")
            if(result == false) return 
            // let namespace = this.show_list[index].namespace
            multi_delete_namespace_resource(namespace,name_list,delete_dr)
            this.refresh()
        },
        // 多选框选项改变就会触发
        onSelect(selection){
            console.log("选项发生变化")
            this.selecteds = selection;
            console.log(this.selecteds)
        },
        // 检查有没有选项选中
        check(){
            // alert(this.selecteds.length)
            if(this.selecteds.length == 0 ){
                this.$Message.error("请选择一项")
                return false
            }  
            return true
        },
        changePage(index) {
            let _start = (index -1) * this.pageSize
            let _end = index * this.pageSize
            this.show_list = this.total_list.slice(_start,_end)
        },
        refresh() {
            // 选中项清空
            this.selecteds = []
            k8s_namespace_post(get_destination_rule_list).then( (response) => {
                this.total_list = response.data
                this.total = response.data.length
                if(this.total < this.pageSize) {
                    this.show_list = this.total_list
                }else {
                    let currentPage = this.$refs.page.currentPage
                    let _start = (currentPage-1) * this.pageSize
                    let _end = currentPage * this.pageSize
                    this.show_list = this.total_list.slice(_start,_end)
                }
            })

        }
    },
    mounted: function() {
        setTimeout(() =>{
            this.refresh();
        },200); 
    }
}
</script>
<style scoped>

</style>